import { ILoadingHelper } from '@/core/interface';

/**
 * 应用加载助手
 *
 * @export
 * @class AppLoadingHelper
 * @implements {ILoadingHelper}
 */
export class AppLoadingHelper implements ILoadingHelper {
	/**
	 * 是否加载中
	 *
	 * @type {boolean}
	 * @memberof AppLoadingHelper
	 */
	isLoading = false;

	/**
	 * 加载记录计数器
	 *
	 * @private
	 * @type {number}
	 * @memberof AppLoadingHelper
	 */
	private loadingCount = 0;

	/**
	 * 全局唯一应用加载助手实例对象
	 *
	 * @private
	 * @static
	 * @type {ILoadingHelper}
	 * @memberof AppLoadingHelper
	 */
	private static helper: ILoadingHelper;

	/**
	 * 获取应用加载助手实例对象
	 *
	 * @static
	 * @return {*}
	 * @memberof AppLoadingHelper
	 */
	public static getInstance() {
		if (!this.helper) {
			this.helper = new AppLoadingHelper();
		}
		return this.helper;
	}

	/**
	 * Creates an instance of AppLoadingHelper.
	 * 私有化构造器，只允许通过getInstance获取实例
	 * @memberof AppLoadingHelper
	 */
	private constructor() {}

	/**
	 * 开始加载
	 *
	 * @param {(string | undefined)} [elementKey]
	 * @return {*}  {void}
	 * @memberof AppLoadingHelper
	 */
	beginLoading(elementKey?: string | undefined): void {
		this.loadingCount += 1;
		if (this.isLoading) {
			return;
		}
		this.isLoading = true;
	}

	/**
	 * 结束加载
	 *
	 * @memberof AppLoadingHelper
	 */
	endLoading(): void {
		this.loadingCount -= 1;
		if (this.loadingCount === 0) {
			this.isLoading = false;
		}
	}
}
